import Menu from "ant-design-vue/es/menu";
// import Icon from "ant-design-vue/es/icon";
import fastEqual from "fast-deep-equal";
import { getI18nKey } from "@/utils/routerUtil";
import { selectKey } from "@/utils/const";
import { mapGetters } from "vuex";
// import { getUnreviewed } from "@/services/user";

const { Item, SubMenu } = Menu;

export default {
  name: "IMenu",
  props: {
    options: {
      type: Array,
      required: true
    },
    theme: {
      type: String,
      required: false,
      default: "dark"
    },
    mode: {
      type: String,
      required: false,
      default: "inline"
    },
    collapsed: {
      type: Boolean,
      required: false,
      default: false
    },
    i18n: Object,
    openKeys: Array
  },
  data() {
    return {
      selectedKeys: [],
      sOpenKeys: [],
      cachedOpenKeys: [],
      mNum: 0,
      iNum: 0,
      haveMsg: false,
      timeInterval: {}
    };
  },
  computed: {
    menuTheme() {
      return this.theme == "light" ? this.theme : "dark";
    },
    ...mapGetters("account", ["iconMap"])
  },
  created() {
    this.updateMenu();
    if (this.options.length > 0 && !this.options[0].fullPath) {
      this.formatOptions(this.options, "");
    }
    // 自定义国际化配置
    if (this.i18n && this.i18n.messages) {
      const messages = this.i18n.messages;
      Object.keys(messages).forEach(key => {
        this.$i18n.mergeLocaleMessage(key, messages[key]);
      });
    }
    // this.getUnreview();
    this.$bus.$on("updateNum", data => {
      if (data.type == "materials") {
        this.mNum = data.val;
      } else {
        this.iNum = data.val;
      }
      let point = document.getElementById("myBadgePoint");
      if (this.mNum != 0 || this.iNum != 0) {
        point.style.display = "inline-block";
      } else {
        point.style.display = "none";
      }
      this.$forceUpdate();
    });
  },
  destroyed() {
    this.$bus.$off("updateNum");
  },
  watch: {
    options(val) {
      if (val.length > 0 && !val[0].fullPath) {
        this.formatOptions(this.options, "");
      }
    },
    i18n(val) {
      if (val && val.messages) {
        const messages = this.i18n.messages;
        Object.keys(messages).forEach(key => {
          this.$i18n.mergeLocaleMessage(key, messages[key]);
        });
      }
    },
    collapsed(val) {
      if (val) {
        this.cachedOpenKeys = this.sOpenKeys;
        this.sOpenKeys = [];
      } else {
        this.sOpenKeys = this.cachedOpenKeys;
      }
    },
    $route: function() {
      this.updateMenu();
    },
    sOpenKeys(val) {
      this.$emit("openChange", val);
      this.$emit("update:openKeys", val);
    }
  },
  methods: {
    // getUnreview() {
    //   getUnreviewed().then(res => {
    //     if (res.data.code == 0) {
    //       console.log(res.data.data);
    //       this.mNum = res.data.data.materialcount;
    //       this.iNum = res.data.data.eqperplaycount;
    //       let point = document.getElementById("myBadgePoint");
    //       if (this.mNum != 0 || this.iNum != 0) {
    //         point.style.display = "inline-block";
    //       } else {
    //         point.style.display = "none";
    //       }
    //     }
    //   });
    // },
    renderIcon: function(h, icon, key) {
      if (this.$scopedSlots.icon && icon && icon !== "none") {
        const vnodes = this.$scopedSlots.icon({ icon, key });
        vnodes.forEach(vnode => {
          vnode.data.class = vnode.data.class ? vnode.data.class : [];
          vnode.data.class.push("anticon");
        });
        return vnodes;
      }
      // return !icon || icon == "none"
      //   ? null
      //   : icon.includes('icon-') ? h('i', { attrs: { class: 'iconfont ' + icon, style: "margin-right:10px" } }) :h(Icon, { props: { type: icon } });
      return !icon || icon == "none"
        ? null
        : h('img', { attrs: { src: require('@/assets/img/menu/'+icon+'.png'), style: "margin-right:10px;width:20px;position:relative;top: -2px" } });
    },
    renderMenuItem: function(h, menu) {
      let tag = "router-link";
      let config = {
        props: { to: menu.fullPath },
        attrs: {
          style: "overflow:hidden;white-space:normal;text-overflow:clip;min-width: 20px;"
        }
      };
      if (menu.meta && menu.meta.link) {
        tag = "a";
        config = {
          attrs: {
            style: "overflow:hidden;white-space:normal;text-overflow:clip;width: 20px",
            href: menu.meta.link,
            target: "_blank"
          }
        };
      }
      return this.getMsg(h, menu, tag, config);
    },
    getMsg(h, menu, tag, config) {
      var val;
      if (menu.path == "materialCheck" || menu.path == "interstitial") {
        val = menu.path == "materialCheck" ? this.mNum : this.iNum;
        if (val != 0) {
          return h(Item, { key: menu.fullPath }, [
            h(tag, config, [
              this.renderIcon(
                h,
                menu.meta ? menu.meta.icon : "none",
                menu.fullPath
              ),
              this.$t(getI18nKey(menu.fullPath)),
              h(
                "span",
                {
                  attrs: {
                    class: "myBadge",
                    style: "margin-left:24px"
                  }
                },
                val
              )
            ])
          ]);
        } else {
          return h(Item, { key: menu.fullPath }, [
            h(tag, config, [
              this.renderIcon(
                h,
                menu.meta ? menu.meta.icon : "none",
                menu.fullPath
              ),
              this.$t(getI18nKey(menu.fullPath))
            ])
          ]);
        }
      } else {
        return h(Item, { key: menu.fullPath }, [
          h(tag, config, [
            this.renderIcon(
              h,
              menu.meta ? menu.meta.icon : "none",
              menu.fullPath
            ),
            this.$t(getI18nKey(menu.fullPath))
          ])
        ]);
      }
    },
    renderSubMenu: function(h, menu) {
      let this_ = this;
      var subItem = [];
      if (menu.path != "broadcast") {
        subItem = [
          h(
            "span",
            {
              slot: "title",
              attrs: {
                style: "overflow:hidden;white-space:normal;text-overflow:clip;"
              }
            },
            [
              this.renderIcon(
                h,
                menu.meta ? menu.meta.icon : "none",
                menu.fullPath
              ),
              this.$t(getI18nKey(menu.fullPath))
            ]
          )
        ];
      } else {
        subItem = [
          h(
            "span",
            {
              slot: "title",
              attrs: {
                style: "overflow:hidden;white-space:normal;text-overflow:clip;"
              }
            },
            [
              this.renderIcon(
                h,
                menu.meta ? menu.meta.icon : "none",
                menu.fullPath
              ),
              this.$t(getI18nKey(menu.fullPath)),
              h("span", {
                attrs: {
                  class: "myBadgePoint",
                  style: "position:relative;top:-1px;left:3px;display:none",
                  id: "myBadgePoint"
                }
              })
            ]
          )
        ];
      }

      let itemArr = [];
      menu.children.forEach(function(item) {
        itemArr.push(this_.renderItem(h, item));
      });
      return h(SubMenu, { key: menu.fullPath }, subItem.concat(itemArr));
    },
    renderItem: function(h, menu) {
      //图标动态获取
      for (let i in this.iconMap) {
        if (menu.path == this.iconMap[i].path) {
          menu.meta.icon = this.iconMap[i].icon;
        }
      }
      let meta = menu.meta;
      if (!meta || !meta.invisible) {
        let renderChildren = false;
        const children = menu.children;
        if (children != undefined) {
          for (let i = 0; i < children.length; i++) {
            const childMeta = children[i].meta;
            if (!childMeta || !childMeta.invisible) {
              renderChildren = true;
              break;
            }
          }
        }
        return menu.children && renderChildren
          ? this.renderSubMenu(h, menu)
          : this.renderMenuItem(h, menu);
      }
    },
    renderMenu: function(h, menuTree) {
      let this_ = this;
      let menuArr = [];
      menuTree.forEach(function(menu, i) {
        menuArr.push(this_.renderItem(h, menu, "0", i));
      });
      return menuArr;
    },
    formatOptions(options, parentPath) {
      options.forEach(route => {
        let isFullPath = route.path.substring(0, 1) == "/";
        route.fullPath = isFullPath
          ? route.path
          : parentPath + "/" + route.path;
        if (route.children) {
          this.formatOptions(route.children, route.fullPath);
        }
      });
    },
    updateMenu() {
      const matchedRoutes = this.$route.matched.filter(
        item => item.path !== ""
      );
      this.selectedKeys = this.getSelectedKey(this.$route);
      let openKeys = matchedRoutes.map(item => item.path);
      openKeys = openKeys.slice(0, openKeys.length - 1);
      if (!fastEqual(openKeys, this.sOpenKeys)) {
        this.collapsed || this.mode === "horizontal"
          ? (this.cachedOpenKeys = openKeys)
          : (this.sOpenKeys = openKeys);
      }
    },
    /**
     * 根据页面route的matched返回路径数组给menu的selectKey数组
     * 因为二级菜单不在menu显示
     * 先判断当前页面是否是隐藏的二级页面，是：进行修改切换，不是：原样返回
     * 根据定义的 selectKey映射数组 将返回数组中最后一个二级path修改为对应的一级path
     * @param route
     */
    getSelectedKey(route) {
      let result = route.matched.map(item => item.path);
      let currRouter = route.path.substring(route.path.lastIndexOf("/") + 1);
      selectKey.forEach(val => {
        if (Object.keys(val).includes(currRouter)) {
          result = route.matched.map(item => item.path);
          let last = result.pop();
          let str = last.substring(last.lastIndexOf("/") + 1);
          result.push(result[result.length - 1] + "/" + val[str]);
        }
      });
      return result;
    }
  },
  render(h) {
    return h(
      Menu,
      {
        props: {
          theme: this.menuTheme,
          mode: this.$props.mode,
          selectedKeys: this.selectedKeys,
          openKeys: this.openKeys ? this.openKeys : this.sOpenKeys
        },
        on: {
          "update:openKeys": val => {
            this.sOpenKeys = val;
          },
          openChange: openKeys => {
            if (openKeys.length > 1) {
              this.openKeys = [openKeys[1]];
            } else if (openKeys.length == 1) {
              this.openKeys = [openKeys[0]];
            } else {
              this.openKeys = [];
            }
          },
          click: obj => {
            obj.selectedKeys = [obj.key];
            this.$emit("select", obj);
          }
        }
      },
      this.renderMenu(h, this.options)
    );
  }
};
